package com.feature.shop.gateway.filter;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import com.feature.core.constant.SecurityConstants;
import com.feature.core.util.JwtUtils;
import com.feature.shop.auth.api.cache.AuthCache;
import com.feature.shop.auth.api.vo.LoginUserVo;
import com.feature.shop.gateway.config.IgnoreWhiteProperties;
import com.feature.shop.gateway.constants.ErrorConstants;
import com.feature.shop.gateway.util.WebFluxUtil;

import reactor.core.publisher.Mono;

/**
 * 网关鉴权
 * 
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {
    private static final Logger log = LoggerFactory.getLogger(AuthFilter.class);

    @Autowired
    private IgnoreWhiteProperties ignoreWhite;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpRequest.Builder mutate = request.mutate();
        mutate.header(SecurityConstants.FROM_SOURCE_REQUEST_HEAD, SecurityConstants.FROM_SOURCE_OUTER);
        String url = request.getURI().getPath();
        // 跳过不需要验证的路径
        if (!ArrayUtils.contains(ignoreWhite.getWhites().toArray(), url)) {
            String token = getToken(request);
            if (StringUtils.isEmpty(token)) {
                return unauthorizedResponse(exchange, "令牌不能为空");
            }
            Integer userid = JwtUtils.getValue(token, SecurityConstants.USER_ID_KEY);
            if (userid == null) {
                return unauthorizedResponse(exchange, "令牌验证失败");
            }
            // 获取用户权限
            LoginUserVo loginUser = AuthCache.getLoginUserInfo(userid);
            if (loginUser == null) {
                return unauthorizedResponse(exchange, "登录状态已过期");
            }
        }
        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }

    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String msg) {
        log.error("[鉴权异常处理]请求路径:{}", exchange.getRequest().getPath());
        return WebFluxUtil.webFluxResponseWriter(exchange.getResponse(), msg, ErrorConstants.UNAUTHORIZED);
    }

    /**
     * 获取请求token
     */
    private String getToken(ServerHttpRequest request) {
        String token = request.getHeaders().getFirst(SecurityConstants.AUTHENTICATION);
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StringUtils.isNotEmpty(token) && token.startsWith(SecurityConstants.PREFIX)) {
            token = token.replaceFirst(SecurityConstants.PREFIX, StringUtils.EMPTY);
        }
        return token;
    }

    @Override
    public int getOrder() {
        return -200;
    }
}